<template>
  <AdVxeModal
    v-bind="$attrs"
    @register="register"
    :id="'select-organization-tree-modal'"
    :title="sendTitle"
    :close-func="handleClose"
    :width="'30%'"
    @ok="handleOk"
  >
    <Form class="p-4 enter-x" :label-col="labelCol" :wrapper-col="wrapperCol">
      <FormItem class="enter-x" :label="t('viewmodal.optOrganization.organization')">
        <ApiTreeSelect
          v-bind="getAttrs"
          v-model:value="organizationIdRef"
          :dropdownMatchSelectWidth="true"
          :showSearch="true"
          :treeDefaultExpandAll="true"
          @options-change="handleOptionsChange"
          @change="handleChange"
        />
      </FormItem>
      <FormItem><div></div></FormItem>
    </Form>
  </AdVxeModal>
</template>
<script lang="ts" setup>
  import type { PropType } from 'vue';
  import { computed, ref, useAttrs } from 'vue';
  import { AdVxeModal, useModalInner } from '@/components/AdVxeModal';
  import { Form } from 'ant-design-vue';
  import { ApiTreeSelect } from '@/components/Form/index';

  import { useI18n } from '@/hooks/web/useI18n';
  import { isFunction } from '@/utils/is';
  import { propTypes } from '@/utils/propTypes';

  import { OrganizationNode, OrganizationTreeNode } from '@/api/identity/model';

  const FormItem = Form.Item;

  defineOptions({ name: 'SelectOrganizationTree' });
  const props = defineProps({
    /** 标题 */
    sendTitle: propTypes.string.def(''),
    /** 确定前回调，返回true关闭窗体 */
    beforeOkFunc: {
      type: Function as PropType<
        (organizationId: string, data: OrganizationNode) => Promise<boolean>
      >,
      default: null,
    },
    // ApiTreeSelect
    api: { type: Function as PropType<(arg?: any) => Promise<Recordable<any>>> },
    params: { type: Object },
    immediate: { type: Boolean, default: true },
    async: { type: Boolean, default: false },
    resultField: propTypes.string.def(''),
    labelField: propTypes.string.def('title'),
    valueField: propTypes.string.def('value'),
    childrenField: propTypes.string.def('children'),
    // TreeSelect
    treeNodeFilterProp: propTypes.string.def(''),
  });

  const { t } = useI18n();
  const attrs = useAttrs();

  const organizationIdRef = ref<string>();
  const organizationNodeRef = ref<OrganizationNode>();
  const organizationTreeNodeRef = ref<OrganizationTreeNode[]>();
  const getAttrs = computed(() => {
    return {
      ...props,
      ...attrs,
    };
  });

  const [register, { closeModal, changeOkLoading }] = useModalInner((data) => {
    organizationIdRef.value = data?.organizationId;
  });

  /** 根据编号设置节点数据 */
  function setNodeById(organizationId?: string) {
    organizationId = organizationIdRef.value;
    // console.log('setNodeById', organizationId);
    if (
      organizationTreeNodeRef.value !== undefined &&
      organizationTreeNodeRef.value != null &&
      organizationId != undefined &&
      organizationId != null &&
      organizationId != ''
    ) {
      // console.log('setNodeById_defined', organizationTreeNodeRef.value);
      organizationNodeRef.value = undefined;
      setOrganizationNode(organizationId, organizationTreeNodeRef.value);
      // console.log('setNodeById_defined', organizationNodeRef.value);
    } else {
      // console.log('setNodeById_undefined', organizationId);
      organizationNodeRef.value = undefined;
    }
  }
  /** 根据编号获取节点数据 */
  function setOrganizationNode(id: string, treeNode: OrganizationTreeNode[]) {
    treeNode.forEach((item) => {
      // console.log('item', item);
      if (item.Id === id) {
        // console.log('findItem', item);
        organizationNodeRef.value = item;
        return;
      } else if (item.Items?.length > 0) {
        setOrganizationNode(id, item.Items);
      }
    });
  }

  /** 处理下拉框数据更改 */
  async function handleOptionsChange(treeData: OrganizationTreeNode[]) {
    // console.log('handleOptionsChange', treeData);
    organizationTreeNodeRef.value = treeData;
    setNodeById(organizationIdRef.value);
  }

  /** 处理选择 */
  const handleChange = (organizationId: string) => {
    // console.log('handleChange', organizationId);
    setNodeById(organizationId);
  };

  /** 处理确定 */
  async function handleOk() {
    // console.log('handleOk', organizationNodeRef.value);
    const { beforeOkFunc } = props;
    if (beforeOkFunc && isFunction(beforeOkFunc)) {
      changeOkLoading(true);
      try {
        const organizationId = organizationIdRef.value || '';
        const organizationNode = organizationNodeRef.value as OrganizationNode;
        const canClose = await beforeOkFunc(organizationId, organizationNode);
        if (canClose) {
          clearFormData();
          closeModal();
        }
      } finally {
        changeOkLoading(false);
      }
    } else {
      clearFormData();
      closeModal();
    }
  }

  /** 处理取消 */
  async function handleClose() {
    clearFormData();
    return true;
  }

  /** 清除表单数据 */
  function clearFormData() {
    organizationIdRef.value = undefined;
    organizationNodeRef.value = undefined;
    organizationTreeNodeRef.value = undefined;
  }

  const labelCol = { span: 6 };
  const wrapperCol = { span: 18 };
</script>
